package com.zh.service.impl;

import com.alibaba.excel.EasyExcel;
import com.zh.file.entity.SysAttachment;
import com.zh.file.mapper.SysAttachmentMapper;
import com.zh.service.TestEasyExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @ClassName TestEasyExcelServiceImpl
 * @date: 2021.01.20 17:38
 * @Author: zhanghang
 */
@Service
public class TestEasyExcelServiceImpl implements TestEasyExcelService {

    @Autowired
    private SysAttachmentMapper sysAttachmentMapper;


    @Override
    public boolean exportExcel(HttpServletRequest request, HttpServletResponse response) {
        List<SysAttachment> sysAttachments = sysAttachmentMapper.selectList(null);
        sysAttachments.forEach(attachment-> System.out.println(attachment));
        export(sysAttachments,request,response);
        return true;
    }

    private void export(List<SysAttachment> list,HttpServletRequest request, HttpServletResponse response){
//        String strUrl = "D:\\excelDoc\\dept"+System.currentTimeMillis()+".xlsx";
//        EasyExcel.write(strUrl,SysAttachment.class).sheet("sheet").doWrite(list);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
            String date = sdf.format(new Date());
            String fileName = "Alarm"+date + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
            EasyExcel.write(response.getOutputStream(), SysAttachment.class).sheet("模板").doWrite(list);
        } catch (Exception e) {
            System.out.println("告警信息下载失败"+e.getMessage());
        }
    }
}
